TARGET          ?= template

COMMON_DIR      ?= ..

CROSS_COMPILE   ?= riscv-none-embed

CC              := $(CROSS_COMPILE)-gcc
AS              := $(CROSS_COMPILE)-as
GXX             := $(CROSS_COMPILE)-g++
OBJDUMP         := $(CROSS_COMPILE)-objdump
OBJCOPY         := $(CROSS_COMPILE)-objcopy

BIN2MEM         := $(COMMON_DIR)/_scripts/bin2mem
BIN2COE         := $(COMMON_DIR)/_scripts/bin2coe

RTLPATH         := $(COMMON_DIR)/../soc/tb
CP              := cp

INCLUDES        += -I$(COMMON_DIR)/_sdk \
                   -I$(COMMON_DIR)/_sdk/systick \
                   -I$(COMMON_DIR)/_sdk/uart \
                   -I$(COMMON_DIR)/_sdk/timer \
                   -I$(COMMON_DIR)/_utilities

LINKFILES       := $(COMMON_DIR)/link.lds

CFLAGS          += -march=rv32im -mabi=ilp32 -mcmodel=medlow
CFLAGS          += -ffunction-sections -fdata-sections

LDFLAGS         ?= -T$(LINKFILES) -nostartfiles -Wl,--gc-sections -Wl,--no-relax

SFILES          += $(COMMON_DIR)/start.S \
                   $(COMMON_DIR)/trap.S

CFILES          += $(COMMON_DIR)/_sdk/systick/systick.c \
                   $(COMMON_DIR)/_sdk/uart/uart.c \
                   $(COMMON_DIR)/_sdk/timer/timer.c \
                   $(COMMON_DIR)/_utilities/xprintf.c

SOBJS           := $(SFILES:.S=.o)
COBJS           := $(CFILES:.c=.o)

OBJS            := $(SOBJS) $(COBJS)

.PHONY: all
all: $(TARGET)

$(TARGET) : $(OBJS)
	$(CC) $(CFLAGS) $(LDFLAGS) $(INCLUDES) $(OBJS) -o $@.elf -Wl,-Map=$@.map
	$(OBJCOPY) -O binary $@.elf $@.bin
	$(OBJDUMP) --disassemble-all $@.elf > $@.DEBUG
	${OBJCOPY} -S -O verilog ${TARGET}.elf $@.data
	$(CP) $@.data $(RTLPATH)/inst_rom.data
	$(CP) $@.coe $(RTLPATH)/inst_rom.coe

$(SOBJS) : %.o: %.S
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(COBJS) : %.o: %.c
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

.PHONY: clean
clean:
	rm -f $(OBJS) $(TARGET).elf $(TARGET).DEBUG $(TARGET).bin *.data *.coe *.map